import { Tabs, Cascader, Table, Input, Button, Checkbox, Divider,Modal } from 'antd';
import axios from '../../axios';
import { useEffect, useState } from 'react';
import "../../assets/css/Goodsmanger.scss"
import XLSX from 'xlsx';
function Goodsmanger() {
    const [headers, setHeaders] = useState([])
    const getHeader = async () => {

        let res = await axios.get("/store/product/tabs/headers", { params: { temp: new Date().getTime() } })

        let arry = []
        res.map(item => {
            arry.push({
                label: `${item.name}(${item.count})`,
                key: item.type,
            })
        })
        setHeaders(arry)
    }
    const [type, setType] = useState(1)
    const getType = (key) => {
        setType(key)
        getList(cateId, keywords, key)
    }


    //层级联动
    const [options, setOptions] = useState([])
    const getoptions = async () => {
        let res = await axios.get("/category/list/tree", {
            params: {
                status: -1,
                type: 1,
                temp: new Date().getTime()
            }
        })
        setOptions(res)
    }
    const [cateId, setcateId] = useState("")
    const onChange = (value) => {
        console.log(value);
        setcateId(arry[arry.length - 1])
        getList(arry[arry.length - 1], keywords, type, page)
    };
    //下面是搜索
    const [keywords, setKeywords] = useState("")
    const searchFun = (e) => {
        // console.log(keywords);
        getList(cateId, keywords, type, page)
    }
    //表格数据
    const [list, setList] = useState([]);
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const getList = async (cateId = "", keywords = "", type = "1", page = 1) => {
        let { list, total } = await axios.get("/store/product/list", {
            params: {
                page,
                limit: 20,
                cateId,
                keywords,
                type,
                temp: new Date().getTime(),
            }
        })
        setTotal(total)
        setList(list)
    }
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: "id"

        },
        {
            title: '商品图',
            dataIndex: 'image',
            key: "image",
            render: (val) => <img style={{ height: "25px", width: "25px" }} src={val} />,// 相当于vue插槽
        },
        {
            title: '商品名称',
            dataIndex: 'keyword',
            ellipsis: true,
            key: "keyword",
            render: (val) => <div className='tabwidth' >{val}</div>,// 相当于vue插槽
        },
        {
            title: '商品售价',
            dataIndex: 'cost',
            key: "cost",

        },
        {
            title: '销量',
            dataIndex: 'sales',
            key: "sales"

        },
        {
            title: '存库',
            dataIndex: 'stock',
            key: "stock"

        },
        {
            title: '排序',
            dataIndex: 'collectCount',
            key: "collectCount"

        },
        {
            title: '添加时间',
            dataIndex: 'addTime',
            key: "addTime",
            render: (val) => {
                let date = new Date(val)
                let Y = date.getFullYear() + '-'
                let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
                let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
                let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
                let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
                return Y + M + D + h + m + s
            }// 相当于vue插槽
        },
        {
            title: '状态',
            dataIndex: 'isShow',
            key: "isShow",
            render: (val) => <b>{val == true ? "上架" : "下架"}</b>,// 相当于vue插槽
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: (_,record) => <Button  onClick={()=>showModal(record)}>详情</Button>,
        },
    ];


    const onChangePage = (value) => {
        console.log(val);
        setPage(val)
        getList(cateId, keywords, type, val)
    }
    useEffect(() => {
        getHeader()
        getoptions()
        getList()
    }, [])
    const defaultCheckedList = columns.map((item) => item.key);
    const [checkedList, setCheckedList] = useState(defaultCheckedList);
    const optionss = columns.map(({ key, title }) => ({
        label: title,
        value: key,
    }));
    const newColumns = columns.map((item) => ({
        ...item,
        hidden: !checkedList.includes(item.key),
    }));

    const changeitem = (e) => {
        // console.log(e.target.checked);
        if (e.target.checked) {
            let arry = []
            optionss.map(item => arry.push(item.value))
            setCheckedList(arry)
        } else {
            setCheckedList([])
        }
    }



    //导出
    // 假设data是你要导出的数据数组
    const data = []
    list.map(item => {
        data.push({
            "商品名称": item.storeName,
            "商品价格": item.price
        })
    })
        ;

    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
        XLSX.writeFile(workbook, "data.xlsx");
    };



    //提示框
    const [row,setRow]=useState({})
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = (row) => {
        console.log(row);
        setRow(row)
      setIsModalOpen(true);
    };
    const handleOk = () => {
      setIsModalOpen(false);
    };
    const handleCancel = () => {
      setIsModalOpen(false);
    };
    return (
        <div className='whitebg'>
            {/* <Button type="primary" onClick={showModal}>
                Open Modal
            </Button> */}
            <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>商品名称：{row.storeName}</p>
               
            </Modal>

            <Tabs
                defaultActiveKey="1"
                items={headers}
                onTabClick={(e) => getType(e)}
            />
            <Cascader
                fieldNames={{ label: "name", value: "id", children: "child" }}
                options={options} onChange={onChange} placeholder="选择商品分类" />
            <Button onClick={(e) => searchFun(e)}>搜索</Button>
            <div>商品搜索</div>
            <Input placeholder="请输入" value={keywords} onChange={(e) => setKeywords(e.target.value)} />

            <Button onClick={exportToExcel}>导出</Button>
            <Checkbox checked={checkedList.length == optionss.length ? true : false} onChange={changeitem}> 全选</Checkbox>
            <Checkbox.Group
                value={checkedList}
                options={optionss}
                onChange={(value) => {
                    setCheckedList(value);
                }}
            />
            <Table

                columns={newColumns}
                expandable={{
                    expandedRowRender: (record) => (
                        <div>
                            <p>商品分类 {record.cateValues}</p>
                            <p>商品价格 {record.price}</p>

                        </div>
                    ),
                }}
                dataSource={list}
                rowKey="id"

                pagination={{
                    defaultCurrent: 1,
                    total,
                    onChange: onChangePage,
                    pageSize: 20,
                    pageSizeOptions: [20, 40, 60, 80, 100]
                }}
            />


        </div>
    );
}

export default Goodsmanger;